
//
//  QZDatePickerViewController.m
//  WeiWeiHaircut
//
//  Created by 上官惠阳 on 15/12/8.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "QZDatePickerViewController.h"

@interface QZDatePickerViewController ()<UIPickerViewDataSource, UIPickerViewDelegate>

@end

@implementation QZDatePickerViewController
{
    NSString *_lastdayStr;
    NSString *_lasthourStr;
    NSString *_lastmintueStr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.minuteStep = StepOneMinute;
    
    [self createPickerView];
    
    for (NSUInteger i = 0; i < 3; i++) {
        [self.datePicker selectRow:[self defaultRowValueForComponent:i] inComponent:i animated:NO];
    }
    //Before call of this all parameters must be setted
    [self pickerView:self.datePicker didSelectRow:[self defaultRowValueForComponent:DayPicker] inComponent:DayPicker];
    
    _lastdayStr = [QZTime stringFromDate:self.date withFormat:@"yyyy年MM日dd日"];
    _lasthourStr = [QZTime stringFromDate:self.date withFormat:@"HH"];
    _lastmintueStr = [QZTime stringFromDate:self.date withFormat:@"mm"];
    
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:self.date];
    [self setPickerView:self.datePicker rowInComponent:HourPicker toIntagerValue:[components hour] decrementing:NO animated:NO];
    [self setPickerView:self.datePicker rowInComponent:MinutePicker toIntagerValue:[components minute]  decrementing:NO animated:NO];
}
#pragma mark - 初始化界面
- (void)createPickerView
{
    // 提示：在使用pickerView之前，必须指定数据源
    self.datePicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];//_pickerView默认是216
    // 指定数据源
    [self.datePicker setDataSource:self];
    // 指定代理
    [self.datePicker setDelegate:self];
    // PickerView默认是没有选中标示的
    [self.datePicker setShowsSelectionIndicator:YES];
    
    [self.view addSubview:self.datePicker];
}
- (NSDate *)date {
    if (!_date) {
        _date = [NSDate date];
    }
    return _date;
}
- (void)setPickerView:(UIPickerView *)pickerView rowInComponent:(NSInteger)component toIntagerValue:(NSInteger)value decrementing:(BOOL)decrementing animated:(BOOL)animated {
    if (decrementing) {
        BOOL valueSetted = NO;
        for (NSInteger i = 0; i < [self realNumberOfRowsInComponent:component]; i++) {
            if ([[self pickerView:pickerView attributedTitleForRow:[pickerView selectedRowInComponent:component] - i forComponent:component].string integerValue] <= value) {
                [pickerView selectRow:[pickerView selectedRowInComponent:component] - i inComponent:component animated:animated];
                valueSetted = YES;
                break;
            }
        }
        if (!valueSetted && component == MinutePicker) {
            [pickerView selectRow:[pickerView selectedRowInComponent:HourPicker] - 1 inComponent:HourPicker animated:animated];
            if ([[self pickerView:pickerView attributedTitleForRow:[pickerView selectedRowInComponent:HourPicker] forComponent:HourPicker].string integerValue] == 0) {
                [pickerView selectRow:[pickerView selectedRowInComponent:DayPicker] - 1 inComponent:DayPicker animated:animated];
            }
        }
    } else {
        BOOL valueSetted = NO;
        for (NSInteger i = 0; i < [self realNumberOfRowsInComponent:component]; i++) {
            if ([[self pickerView:pickerView attributedTitleForRow:[pickerView selectedRowInComponent:component] + i forComponent:component].string integerValue] >= value) {
                [pickerView selectRow:[pickerView selectedRowInComponent:component] + i inComponent:component animated:animated];
                valueSetted = YES;
                break;
            }
        }
        if (!valueSetted && component == MinutePicker) {
            [pickerView selectRow:[pickerView selectedRowInComponent:HourPicker] + 1 inComponent:HourPicker animated:animated];
            if ([[self pickerView:pickerView attributedTitleForRow:[pickerView selectedRowInComponent:HourPicker] forComponent:HourPicker].string integerValue] == 0) {
                [pickerView selectRow:[pickerView selectedRowInComponent:DayPicker] + 1 inComponent:DayPicker animated:animated];
            }
        }
    }
}
- (NSInteger)realNumberOfRowsInComponent:(NSInteger)component {
    NSInteger numberOfRows = 0;
    switch (component) {
        case DayPicker:
            numberOfRows = 30;
            break;
        case HourPicker:
            numberOfRows = 24;
            break;
        case MinutePicker:
            numberOfRows = 60 / self.minuteStep;
            break;
    }
    
    return numberOfRows;
}
- (NSString *)stringDateForRow:(NSUInteger)row {
    NSDate *date = [self dateForRow:row];
    if ([self isDate:date sameDayAsDate:[NSDate date]]) {
        return NSLocalizedString(@"今天", @"Current day indicator");
    }
    return [self.dateFormatter stringFromDate:date];
}
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        _dateFormatter.dateFormat = @"MMM d ccc";
    }
    return _dateFormatter;
}
#pragma mark - NSDate operations
-(BOOL)isDate:(NSDate*)date1 sameDayAsDate:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}
#pragma mark - Properties
- (UIColor *)mainColor {
    if (!_mainColor) {
        _mainColor = [UIColor whiteColor];
    }
    return _mainColor;
}
- (NSDate *)dateForRow:(NSInteger)row {
    row = row - [self defaultRowValueForComponent:DayPicker];
    NSDate * date = [self.date dateByAddingTimeInterval:60 * 60 * 24 * row];
    return [[NSCalendar currentCalendar] dateBySettingHour:0 minute:0 second:0 ofDate:date options:0];
}
- (NSInteger)defaultRowValueForComponent:(NSInteger)component {
    return [self realNumberOfRowsInComponent:component] * kRowsMultiplier / 2;
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self realNumberOfRowsInComponent:component] * kRowsMultiplier;
}
#pragma mark - UIPickerViewDelegate

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
   return [self getWidthWithComponet:component];
}

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self getContentForRow:row forComponent:component];
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, [self getWidthWithComponet:component], 35)];
    label.textColor = self.mainColor;
    label.attributedText = [self getContentForRow:row forComponent:component];
    
    label.font = [UIFont systemFontOfSize:17];
    
    return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *dayStr = _lastdayStr;
    NSString *hourStr = _lasthourStr;
    NSString *mintueStr = _lastmintueStr;
    
    switch (component) {
        case DayPicker:
            dayStr = [QZTime stringFromDate:[self dateForRow:row] withFormat:@"yyyy年MM月dd日"];
            _lastdayStr = dayStr;
            break;
        case HourPicker:
            hourStr  = [NSString stringWithFormat:@"%02ld", row % [self realNumberOfRowsInComponent:component]];
            _lasthourStr = hourStr;
            break;
        case MinutePicker:
            mintueStr = [NSString stringWithFormat:@"%02lu", row % [self realNumberOfRowsInComponent:component] * self.minuteStep];
            _lastmintueStr = mintueStr;
            break;
    }
    _showLabel.text = [NSString stringWithFormat:@"%@ %@:%@",dayStr,hourStr,mintueStr];
}
//获取宽度
-(CGFloat)getWidthWithComponet:(NSInteger)component
{
    CGFloat width = self.datePicker.frame.size.width;
    CGFloat itemWidth = 0;
    switch (component) {
        case DayPicker:
            itemWidth = width * (11 / 23.0);
            break;
        case HourPicker:
            itemWidth = width * (6 / 23.0);
            break;
        case MinutePicker:
            itemWidth = width * (6 / 23.0);
            break;
    }
    
    return itemWidth;
}
//获取内容
-(NSAttributedString *)getContentForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = @"";
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    switch (component) {
        case DayPicker:
            title = [self stringDateForRow:row];
            [paragraphStyle setAlignment:NSTextAlignmentRight];
            break;
        case HourPicker:
            title = [NSString stringWithFormat:@"%02ld", row % [self realNumberOfRowsInComponent:component]];
            [paragraphStyle setAlignment:NSTextAlignmentCenter];
            
            break;
        case MinutePicker:
            title = [NSString stringWithFormat:@"%02lu", row % [self realNumberOfRowsInComponent:component] * self.minuteStep];
            [paragraphStyle setAlignment:NSTextAlignmentLeft];
            
            break;
    }
    
    
    return [[NSAttributedString alloc] initWithString:title attributes:
            @{NSForegroundColorAttributeName: self.mainColor,
              NSParagraphStyleAttributeName: paragraphStyle}];
}
-(void)setShowLabel:(UILabel *)showLabel
{
    showLabel.text = [QZTime stringFromDate:self.date withFormat:@"yyyy年MM月dd日 HH:mm"];
    _showLabel = showLabel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
